home *** CD-ROM | disk | FTP | other *** search
- Path: news1.h1.usa.pipeline.com!usenet
- From: grantp@usa.pipeline.com(Pete)
- Newsgroups: comp.lang.c++
- Subject: Re: Comparing Struct elements
- Date: 1 Feb 1996 00:02:51 GMT
- Organization: Kalevi, Inc.
- Message-ID: <4eovvb$jv8@news1.usa.pipeline.com>
- NNTP-Posting-Host: pipe7.h1.usa.pipeline.com
- X-PipeUser: grantp
- X-PipeHub: usa.pipeline.com
- X-PipeGCOS: (Pete)
- X-Newsreader: Pipeline USA v3.3.0
-
- On Jan 31, 1996 15:30:50 in article <Comparing Struct elements>,
- 'bhardwaj@ccs.neu.edu (saurabh bhardwaj)' wrote:
-
-
- >Hello,
- >
- >I've been trying to compare structure elements using the if Statement.
- Here
- >is the code:
- >
- >
- >double NumericVal(ClassRec& LetGrade){
- >
- >cout << "assgning struct member usin . " << LetGrade.
- >Grade << '\n';
- >if(LetGrade.Grade == "A") return(4.000);
- >else if(LetGrade.Grade == "A-") return(3.666);
- >else if(LetGrade.Grade == "B+") return(3.333);
- >else return 0;
- >}
- >
- >where LetGrade is the following struct:
- >
- >struct ClassRec {
- >char Grade[3];
- >int QH;
- >char Name[10];
- >};
- >
- >I can't seem to compare the elements of the Grade[3] with "A" or "A-" or
- "B+"
- >The function invariable returns 0. I've also tried using the -> operator.
- It
- >doesn't work either!!! Anyone know why??? I'll appreciate any help.
- >
- You have three choices -- well, actually it's only two.
-
- 1. Use strcmp() instead ==. When you code (foo == "foo"), you are
- actually comparing the addresses of the strings. They're never equal.
-
- 2. Define operator== for your struct that takes a pointer to a character
- array as an argument. Of course, inside this operator, you should use
- strcmp, so this solution is almost like 1.
-
- 3. Use a string class instead of raw strings. If using MFC, for example,
- you could change your structure definition to something like
-
- struct ClassRec
- {
- CString Grade;
- int QH;
- CString Name;
- };
-
- On a "real" program, solution #3 is the best one. On a school project,
- take your pick.
-
- Anyway, the bottom line here is that you can't compare complex
- structures using the "==" unless you have defined an operator
- for them. A string is not a simple type as it is really an array of
- characters. Consequently, you must use some other means
- of comparing the equivalence of a pair of strings. The standard
- C library function strcmp() is just such a tool.
-
- --
- Pete Grant
- Kalevi, Inc.
- Object Oriented Software Development
-